<template>
	<view>
		<u-popup :show="showBottomLogin" @close="closeBottomLogin" :closeOnClickOverlay="false" :safeAreaInsetBottom="true" round="10px" mode="bottom">			
			<view class="dflex jcsb pb12 aic wrap w100percent">
				<view class="dflex aifs">
					<view class="line_box" :style="'background-color:' + app.theme.mainColor + ';'"></view>
					<text class="f16 fbold ml5">用户登录</text>
					<text @click="getOtherCode" class="f14 fbold ml5 c777777">（未注册用户验证后自动注册）</text>
				</view>
				<view class="dflex" @click.stop="closeBottomLogin">
					<text class="f14">关闭</text>
				</view>
			</view>
			
			<!-- #ifdef MP-WEIXIN -->
			<view class="login_form dflex cflex gap12" style="padding: 30px;" v-show="showOne">
				<u-button open-type="getPhoneNumber"
					type="primary" 
					@getphonenumber="decryptPhoneNumber"
					:color="mainColor"
					customStyle="height: 45px;"
				>本机手机号一键登录
				</u-button>
				<u-button 
					type="primary"
					:plain="true"
					:color="mainColor"
					customStyle="height: 45px;"
					@click="showOtherClick"
				>其他手机号验证码登录
				</u-button>
				<view class="user_check mt12 dflex aic" @click="userCheckClick">
					<radio shape="circle" :checked="userCheck" :color="mainColor" style="transform:scale(0.7);"></radio>
					<u-parse :content="content" :tagStyle="style"></u-parse>
				</view>
			</view>
			<!-- #endif -->
			
			<!-- #ifdef MP-KUAISHOU -->
			<view class="login_form dflex cflex gap12" style="padding: 30px;" v-show="showOne">
				<u-button open-type="getPhoneNumber"
					type="primary" 
					@getphonenumber="decryptPhoneNumber"
					:color="mainColor"
					customStyle="height: 45px;"
				>快手用户一键登录
				</u-button>
				<u-button 
					type="primary"
					:plain="true"
					:color="mainColor"
					customStyle="height: 45px;"
					@click="showOtherClick"
				>其他手机号验证码登录
				</u-button>
				<view class="user_check mt12 dflex aic" @click="userCheckClick">
					<radio shape="circle" :checked="userCheck" :color="mainColor" style="transform:scale(0.7);"></radio>
					<u-parse :content="content" :tagStyle="style"></u-parse>
				</view>
			</view>
			<!-- #endif -->

			<!-- #ifdef MP-TOUTIAO -->
			<view class="login_form dflex cflex gap12" style="padding: 30px;" v-show="showOne">
				<u-button type="primary" @tap="getDyInfo"
					:color="app.theme.mainColor" customStyle="height: 45px;">抖音用户一键登录
				</u-button>
				<u-button type="primary" :plain="true" :color="app.theme.mainColor" customStyle="height: 45px;"
					@click="showOtherClick">其他手机号验证码登录
				</u-button>
				<view class="user_check mt12 dflex aic" @click="userCheckClick">
					<radio shape="circle" :checked="userCheck" :color="app.theme.mainColor" style="transform:scale(0.7);">
					</radio>
					<u-parse :content="content" :tagStyle="style"></u-parse>
				</view>
			</view>
			<!-- #endif -->
		
			<view class="login_form cflex" style="padding: 0 30px 30px 30px;" v-show="showOther">
				<u-form labelPosition="left" :rules="rules" :model="registerModel" ref="registerForm">

					<u-form-item label="手机号" prop="register.phone" ref="phone" labelWidth="70">
						<u--input v-model="registerModel.register.phone" border="bottom" placeholder="请输入手机号码"
							maxlength="11" type="number"></u--input>
					</u-form-item>

					<u-form-item label="验证码" prop="register.code" labelWidth="70" ref="sendCode">
						<u--input v-model="registerModel.register.code" border="bottom" placeholder="请填写验证码"
							maxlength="4" type="number"></u--input>
						<u-button slot="right" @click="getCode" :color="app.theme.mainColor" size="normal" throttleTime="1000"
							:disabled="disabled1" customStyle="miniWidth:100px;width:100px;">
							<text style="color: #fff;">{{ tips }}</text>
						</u-button>
					</u-form-item>

					<view style="margin-top: 20px;">
						<u-button :color="app.theme.mainColor" :loading="loginLoading" loadingMode="circle" loadingText="登陆中" @click="loginOrRegister" :disabled="checkGetCode"  customStyle="height: 45px;">
							<text style="color: #fff;">登录/注册</text>
						</u-button>
					</view>

					<view class="user_check mt12 dflex aic" @click="userCheckClick">
						<radio shape="circle" :checked="userCheck" :color="app.theme.mainColor" style="transform:scale(0.7);">
						</radio>
						<u-parse :content="content" :tagStyle="style"></u-parse>
					</view>

				</u-form>

				<u-code ref="uCode" @change="codeChange" :seconds="countdown" :keep-running="true" changeText="x秒后获取"
					@start="disabled1 = true" @end="disabled1 = false">
				</u-code>

				<u-modal :show="showRegister" title="确认同意注册" content="您已阅读并同意《用户服务协议》以及《隐私权政策》？" :showCancelButton="true"
					@confirm="ensureRegister" @cancel="closeRegister" @close="closeRegister">
				</u-modal>
				
				<!-- #ifdef MP-WEIXIN -->
				<view class="df mt12">
					<u-divider text="更多登录方式"></u-divider>
				</view>
				
				<view class="cflex f14 taligncenter jcc">
					<u-button open-type="getPhoneNumber" 
						type="success" 
						:color="mainColor"
						@getphonenumber="decryptPhoneNumber"
						customStyle="height: 45px;"
						:plain="true"
					>本机手机号一键登录
					</u-button>
				</view>
				<!-- #endif -->

			</view>
		</u-popup>
	</view>
</template>

<script>
	const global = getApp().globalData
	export default {
		name: "buttomPhoneLogin",
		data() {
			return {
				app: {
					name: global.appName,
					windowInfo: '',
					HeaderWidth: '',
					global: global,
					theme : global.theme
				},
				domain : global.domain,
				registerModel: {
					register: {
						phone: '',
						code: '',
					}
				},
				disabled1: false,
				rules: {
					// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
					'register.phone': [{
						type: 'string',
						required: true,
						message: '请输入手机号码',
						trigger: ['change', 'blur']
					}, {
						validator: (_rule, value, _callback) => {
							return uni.$u.test.mobile(value);
						},
						trigger: ["change", "blur"],
						message: '请输入正确的手机号码',
					}],
					'register.code': [{
						type: 'string',
						max: 4,
						required: true,
						message: '请输入验证码',
						trigger: ["change", "blur"],
					}, {
						validator: (_rule, value, _callback) => {
							return uni.$u.test.code(value, 4);
						},
						trigger: ["change", "blur"],
						message: '请输入4位数字验证码',
					}]
				},
				tips: '',
				loginLoading: false,
				checkGetCode: true,
				userCheck: false,
				content: `<p>我已阅读并同意<a href=\"\/sonPages\/about\/service\">《用户服务协议》</a>以及<a href=\"\/sonPages\/about\/privacy\">《隐私权政策》</a></p>`,
				style: {
					// 字符串的形式
					p: 'font-size:12px',
					a: 'font-size:12px;color:#333;text-decoration: underline;'
				},
				showRegister: false,
				countdown: 45,
				showBottomLogin : false,				
				showOne : true,
				showOther : false,
				dy_code : '',
				wx_code : '',		
				kuaishou_code : '',			
				clickNum : 0
			};
		},
		props: {
			mainColor: {
				type: String,
				default: global.theme.mainColor	
			}
		},
		onReady() {
			// #ifdef MP-WEIXIN
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.registerForm.setRules(this.rules)
			// #endif
		},
		methods: {
			refreshMy() {
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = routes[routes.length - 1].route // 
				if (curRoute == "sonPages/my/my") {
					uni.redirectTo({
						url:'/sonPages/my/my'
					})
				}
			},
			// #ifdef MP-TOUTIAO
			getDyInfo() {
				uni.getUserProfile({
						provider: 'toutiao',
						success: (infoRes) => {
							uni.showLoading({
								title: '登录中...',
							});
							uni.request({
								url: this.domain + 'api/v1/users_dy',
								method: 'POST',
								data: {
									avatar : infoRes.userInfo.avatarUrl,
									nickName : infoRes.userInfo.nickName,
									toutiao_code : this.dy_code 
								},
								success: (res) => {									
									if(res.data.status == 'success') {
										// console.log('res.data.key',res.data.key);
										uni.setStorageSync("access_member_info", res.data);
										// uni.setStorageSync("login_type", "phone");
										this.showBottomLogin = false
										uni.showToast({
											title: '登录成功，请继续操作',
											icon:'none',
											duration:2000
										})
										// refreshLoginStatus这个每个父页面要做的事情是不一样的
										// 不要看着名字一样就批量修改
										// refreshMy当用户再我的页面点击登陆的时候有效
										this.refreshMy()
										this.$emit('refreshLoginStatus') 
										// console.log(uni.getStorageSync("code_key"));
									}									
									
									if(res.data.status == 'fail') {
										this.showBottomLogin = false
										uni.showToast({
											title: res.data.message,
											icon:'none',
											duration:2000
										})
									}
								},
								fail: (err) => {
									console.log('err', err);
								}
							})
						},
						fail: (err) => {
							console.log('err', err);
						}
			    });	
			},
			// #endif
			getOtherCode() {
				this.clickNum++
				if (this.clickNum > 5) {
					// console.log('gogogo')
					uni.request({
						url: this.domain + 'api/v1/getOtherCode',
						method: 'POST',
						data: {
							key: uni.getStorageSync("code_key")
						},
						success: (res) => {
							uni.showToast({
								title: res.data.code,
								icon: 'none'
							})
						},
						fail: (res) => {}
					})
				}
			},
			showOtherClick() {
				this.showOne = false
				this.showOther = true
			},
			openLoginPopup() {
				// #ifdef MP-WEIXIN
				this.getWxCode()
				// #endif
				
				// #ifdef MP-BAIDU || H5
				this.showBottomLogin = true
				this.showOtherClick()
				// #endif
				
				// #ifdef MP-TOUTIAO
				this.getTouTiaoCode()
				// this.showBottomLogin = true
				// this.showOtherClick()
				// #endif
				
				// #ifdef MP-KUAISHOU
				this.getKuaiShouCode()
				// this.showBottomLogin = true
				// this.showOtherClick()
				// #endif
			},
			closeBottomLogin() {
				// console.log('this.showBottomLogin1', this.showBottomLogin)
				this.showBottomLogin = false
				// console.log('this.showBottomLogin2', this.showBottomLogin)
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: '获取验证码...',
						mask: true
					});
					uni.request({
						url: this.domain + 'api/v1/verificationCodes',
						method: 'POST',
						data: {
							phone: this.registerModel.register.phone
						},
						success: (res) => {
							uni.hideLoading();
							if (res.statusCode != 201) {
								uni.showToast({
									title: res.data.phone[0],
									icon:'error'
								})
							} else {
								// console.log('res.data.key',res.data.key);
								this.checkGetCode = false;
								uni.setStorageSync("code_key", res.data.key);
								uni.setStorageSync("tempPhone", this.registerModel.register.phone);
								uni.setStorageSync("getTime", Math.floor(Date.now() / 1000));
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
								// console.log(uni.getStorageSync("code_key"));
							}
						},
						fail: (res) => {}
					})
				} else {
					uni.showToast({
						title: '倒计时结束后再发送',
						icon:'error'
					})
				}
			},
			loginOrRegister() {
				if (this.userCheck == false) {
					this.showRegister = true
				} else {
					this.$refs.registerForm.validate().then(res => {
						// console.log("注册流程开始")
						uni.showLoading({
							title: '登录中...',
							mask: true
						});
						uni.request({
							// #ifdef MP-WEIXIN || MP-TOUTIAO
							url:this.domain + 'api/v1/users',
							// #endif
							// #ifdef H5
							url:this.domain + 'api/v1/users_h5',
							// #endif
							method: 'POST',
							data: {
								verification_key: uni.getStorageSync("code_key"),
								verification_code: this.registerModel.register.code,
								phone : this.registerModel.register.phone,						
								wechat_code : this.wx_code,			
								douyin_code : this.dy_code,								
								// #ifdef MP-WEIXIN
								provider : 'weixin',
								// #endif
								// #ifdef MP-TOUTIAO
								provider : 'toutiao',
								// #endif
								// #ifdef MP-KUAISHOU
								provider : 'toutiao',
								// #endif
							},
							success: (res) => {
								uni.hideLoading();
								if (res.statusCode != 201) {
									// console.log(res);
									uni.showToast({
										title:res.data.message,
										icon:'none'
									})
									// uni.$u.toast(res.data.message);
								}
								if (res.data.status == 'success') {
									// console.log(res.data);
									uni.setStorageSync("access_member_info", res.data);
									// uni.setStorageSync("login_type", "phone");
									uni.showToast({
										title: '登录成功，请继续操作',
										icon:'none',
										duration:2000
									})
									this.showBottomLogin = false
									// refreshLoginStatus这个每个父页面要做的事情是不一样的
									// 不要看着名字一样就批量修改
									this.refreshMy()
									this.$emit('refreshLoginStatus')
								}
								
								if(res.data.status == 'fail') {
									this.showBottomLogin = false
									uni.showToast({
										title: res.data.message,
										icon:'none',
										duration:2000
									})
								}
							},
							fail: (res) => {}
						})
					}).catch(errors => {
						// console.log(errors);
						uni.showToast({
							title: '请正确填写表单内容',
							icon:'error'
						})
					})
				}
			},
			userCheckClick() {
				this.userCheck = !this.userCheck;
				// console.log(this.userCheck)
			},
			codeChange(text) {
				this.tips = text;
			},
			ensureRegister() {
				this.showRegister = false
				this.userCheck = true
				this.loginOrRegister()
			},
			closeRegister() {
				this.showRegister = false
			},
			getWxCode() {
				uni.login({
					provider:'weixin',
					success: (res) => {
						this.wx_code = res.code
						this.showBottomLogin = true
						this.showOne = true
						this.showOther = false
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			getTouTiaoCode() {
				uni.login({
					provider:'toutiao',
					success: (res) => {
						this.dy_code = res.code
						this.showBottomLogin = true
						this.showOne = true
						this.showOther = false
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			getKuaiShouCode() {
				uni.login({
					provider:'kuaishou',
					success: (res) => {
						this.kuaishou_code = res.code
						this.showBottomLogin = true
						this.showOne = true
						this.showOther = false
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			decryptPhoneNumber(e) {
				this.userCheck = true
				this.errMsg = e.detail.errMsg
				this.iv = e.detail.iv
				this.encryptedData  = e.detail.encryptedData
				// console.log('e.detail.encryptedData', e.detail.encryptedData)
				// console.log('this.code', this.code)
				//用户取消这个值就获取不到，就不要发请求到服务器了
				if(e.detail.encryptedData && (this.wx_code != '' || this.dy_code != '' || this.kuaishou_code != '')) {
					//加一个延时，防止code没获取到
					setTimeout(()=>{
						uni.showLoading({
							title:'加载中',
							mask: true
						})
						uni.request({
							url: this.domain + 'api/v1/users_decrypt_phone_number',
							method: 'POST',
							data: {
								errMsg:this.errMsg,
								iv: this.iv,
								encryptedData : this.encryptedData,
								// #ifdef MP-WEIXIN
								wechat_code : this.wx_code,
								provider : 'weixin',
								// #endif
								// #ifdef MP-TOUTIAO 
								toutiao_code : this.dy_code,
								provider : 'toutiao',
								// #endif
								// #ifdef MP-KUAISHOU
								kuaishou_code : this.kuaishou_code,
								provider : 'kuaishou',
								// #endif
							},
							success: (res) => {	
								uni.hideLoading()
								if (res.statusCode != 201) {
									// console.log(res);
									uni.showToast({
										title: res.data.message,
										icon:'error'
									})
									// uni.$u.toast(res.data.message);
								} 
								
								if(res.data.status == 'success') {
									// console.log(res.data);
									uni.setStorageSync("access_member_info", res.data);
									// uni.setStorageSync("login_type", "phone");
									this.showBottomLogin = false
									uni.showToast({
										title: '登录成功，请继续操作',
										icon:'none',
										duration:2000
									})
									// refreshLoginStatus这个每个父页面要做的事情是不一样的
									// 不要看着名字一样就批量修改									
									this.refreshMy()
									this.$emit('refreshLoginStatus') 
								}							
								
								if(res.data.status == 'fail') {
									this.showBottomLogin = false
									uni.showToast({
										title: res.data.message,
										icon:'none',
										duration:2000
									})
								}
							},
							fail: (res) => {}
						})
					},1000)
				}
			}
		}
	}
</script>

<style>
</style>